package org.example.aitest.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import java.util.stream.Collectors;

/**
 * Repeatable 过滤器

 */
public class RepeatableFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        /*ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest
                && StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE))
        {
            requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
        }
        if (null == requestWrapper)
        {
            chain.doFilter(request, response);
        }
        else
        {
            chain.doFilter(requestWrapper, response);
        }*/
        if(!(request instanceof HttpServletRequest)){
            chain.doFilter(request,response);
            return;
        }

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        try {
            if(httpRequest.getContentLength() > 0){
                XssHttpServletRequestWrapper wrapper = new XssHttpServletRequestWrapper(httpRequest);
                chain.doFilter(wrapper,response);
            }else {
                chain.doFilter(request,response);
            }

        }catch (Exception e){
            System.out.println("错误"+getRequestHeaders(httpRequest)+"--------===="+e.getMessage());
            throw new ServletException("Network error"+e);
        }
    }

    private String getRequestHeaders(HttpServletRequest request) {
        return Collections.list(request.getHeaderNames())
                .stream()
                .map(name -> name + "=" + request.getHeader(name))
                .collect(Collectors.joining(", "));
    }

    public boolean isJsonRequest(HttpServletRequest request)
    {
        String contentType = request.getContentType();
        return contentType != null && contentType.toLowerCase().startsWith("application/json");
//        String header = super.getHeader(HttpHeaders.CONTENT_TYPE);
//        return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE);
    }

    @Override
    public void destroy()
    {

    }
}
